<template>
  <div class="shopcart-container">
    <!-- 全选 清空 -->
    <div class="cart_header">
      <div class="cart_title">
        <!-- 移除 @click 绑定，让 v-model 单独控制状态 -->
        <van-checkbox checked-color="#000000" icon-size="18" v-model="isCheckedAll">
          全选
        </van-checkbox>
      </div>
      <div class="cart_clear" @click="onClickDeleteAll">
        <van-icon name="delete" />
        <span>清空</span>
      </div>
    </div>
    <!-- 商品列表区域 -->
    <div style="background-color: white;">
      <van-row v-for="(item, i) in cartList" :key="item.id" type="flex" align="center">
        <van-col span="2">
          <van-checkbox v-model="item.is_checked" @change="onCheckedChange(item)" />	
        </van-col>
        <van-col span="5">
          <van-image :src="item.pic" width="80" height="80" @error="handleImageError(item)" :alt="item.title" />
        </van-col>
        <van-col span="17">
          <van-row class="van-multi-ellipsis--l2 title">{{ item.title }}</van-row>
          <van-row type="flex" align="center">
            <van-col span="8" class="price">¥{{ item.price }}</van-col>
            <van-col span="16" class="opration">
              <van-stepper v-model="item.count" @change="onCountChanged(item)" integer />
              <van-button text="删除" size="small" @click.prevent="onClickDeleteCartItem(item.id)" />
            </van-col>
          </van-row>
        </van-col>
      </van-row>
    </div>
    <!-- 商品结算区域 -->
    <van-cell title="商品结算" value="总计不含运费"></van-cell>
    <van-cell>
      <template #title>
        已勾选商品<span class="red">{{ getCheckedCount }}</span>
        件，总价
        <span class="red">¥{{ getCheckedAmount }}</span>
      </template>
    </van-cell>
    <!-- 结算按钮 -->
    <van-button type="primary" size="large" @click="onClickCreateOrder">去结算</van-button>
    <!-- 加载状态 -->
    <van-loading v-show="isLoading" />
  </div>
</template>

<script>
import { showConfirmDialog, showToast } from 'vant';

export default {
  data() {
    return {
      cartList: [],
      isLoading: false,
      defaultImage: 'https://via.placeholder.com/80x80',
      maxImageRetries: 3,
      retryBaseDelay: 1000,
      retryExponent: 2
    };
  },
  computed: {
    // 计算勾选记录总数
    getCheckedCount() {
      return this.cartList.reduce((sum, item) => item.is_checked ? sum + 1 : sum, 0);
    },
    // 计算是否全部勾选 - 使用 setter/getter 模式
    isCheckedAll: {
      get() {
        return this.cartList.length > 0 && this.cartList.every(item => item.is_checked);
      },
      set(value) {
        // 直接更新商品选中状态
        this.cartList.forEach(item => {
          item.is_checked = value;
        });
        this.saveCartToStorage(this.cartList);
      }
    },
    // 计算勾选商品总价
    getCheckedAmount() {
      return this.cartList.reduce(
        (amount, item) => item.is_checked ? amount + item.price * item.count : amount,
        0
      );
    }
  },
  methods: {
    // 错误处理方法
    handleError(message) {
      console.error(message);
      showToast(message + '，请稍后重试');
    },
    
    // 从本地存储获取购物车数据
    getCartFromStorage() {
      return JSON.parse(localStorage.getItem('cart') || '[]');
    },
    
    // 保存购物车到本地存储
    saveCartToStorage(cart) {
      localStorage.setItem('cart', JSON.stringify(cart));
    },
    
    // 处理图片加载错误
    async handleImageError(item) {
      if (!item.retryCount) {
        item.retryCount = 0;
      }
      if (item.retryCount < this.maxImageRetries) {
        item.retryCount++;
        const retryDelay = this.retryBaseDelay * Math.pow(this.retryExponent, item.retryCount - 1);
        showToast(`商品 ${item.title} 的图片加载失败，正在重试（第 ${item.retryCount} 次）`);
        await new Promise(resolve => setTimeout(resolve, retryDelay));
        item.pic = item.pic; // 触发重新加载
      } else {
        showToast(`商品 ${item.title} 的图片加载失败，将显示默认图片`);
        item.pic = this.defaultImage;
        this.saveCartToStorage(this.cartList); // 更新本地存储
      }
    },
    
    // 获取用户购物车数据
    getCartData() {
      try {
        this.isLoading = true;
        this.cartList = this.getCartFromStorage();
        // 确保每个商品都有 is_checked 属性
        this.cartList.forEach(item => {
          if (item.is_checked === undefined) {
            item.is_checked = true;
          }
        });
      } catch (error) {
        this.handleError('获取购物车列表失败');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 触发更改购物商品数量
    onCountChanged(item) {
      if (item.count <= 0) {
        item.count = 1; // 防止数量小于等于0
        showToast('商品数量不能小于1');
        return;
      }
      
      try {
        this.isLoading = true;
        // 直接更新本地数据
        const index = this.cartList.findIndex(cartItem => cartItem.id === item.id);
        if (index !== -1) {
          this.cartList[index].count = item.count;
          this.saveCartToStorage(this.cartList);
        }
      } catch (error) {
        this.handleError('更新商品数量失败');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 触发更改购物商品选中状态
    onCheckedChange(item) {
      try {
        this.isLoading = true;
        // 直接更新本地数据
        const index = this.cartList.findIndex(cartItem => cartItem.id === item.id);
        if (index !== -1) {
          this.cartList[index].is_checked = item.is_checked;
          this.saveCartToStorage(this.cartList);
        }
      } catch (error) {
        this.handleError('更新商品选中状态失败');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 触发删除购物商品
    async onClickDeleteCartItem(id) {
      try {
        const shouldDelete = await showConfirmDialog({
          message: '客官，您确定删除该商品吗?'
        });
        if (shouldDelete) {
          this.isLoading = true;
          // 直接更新本地数据
          this.cartList = this.cartList.filter(item => item.id !== id);
          this.saveCartToStorage(this.cartList);
        }
      } catch (error) {
        this.handleError('删除商品失败');
      } finally {
        this.isLoading = false;
      }
    },
    
    // 触发清空
    async onClickDeleteAll() {
      const shouldDeleteAll = await showConfirmDialog({
        message: '客官，您确定清空购物车吗?'
      });
      if (shouldDeleteAll) {
        try {
          this.isLoading = true;
          // 直接更新本地数据
          this.cartList = [];
          this.saveCartToStorage(this.cartList);
        } catch (error) {
          this.handleError('清空购物车失败');
        } finally {
          this.isLoading = false;
        }
      }
    },
    
    // 触发创建订单
        onClickCreateOrder() {
          const selectedItems = this.cartList.filter(item => item.is_checked);
          
          if (selectedItems.length === 0) {
            showToast("请选择要结算的商品");
            return;
          }
          
          // 将选中的商品信息保存到本地存储
          localStorage.setItem('selectedCartItems', JSON.stringify(selectedItems));
		  
          
          // 跳转到订单创建页面
          this.$router.push({
            name: "orderCreate"
          });
        }
      },
  mounted() {
    this.getCartData();
  }
};
</script>

<style lang="less" scoped>
.shopcart-container {
  padding: 0px 10px;

  .cart_header {
    padding: 10px;
    margin: 10px 0;
    height: 20px;
    background-color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.van-checkbox {
  justify-content: center;
}

.title {
  padding: 5px 5px;
  font-size: 12px;
  line-height: 20px;
}

.price {
  padding-left: 10px;
  text-align: left;
  font-size: 16px;
  font-weight: bold;
  color: red;
  display: flex;
  align-items: center;
}

.opration {
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.red {
  color: red;
  font-weight: bold;
  font-size: 16px;
}
</style>